package com.fbli.upload.homework;

import com.fbli.upload.Utils.StreamUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPFileDownloadServer {
    public static void main(String[] args) throws IOException {
        //1.让服务端在本机监听8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务端在8888端口监听....");
        //2.等待连接
        Socket socket = serverSocket.accept();
        //3.读取客户端发送的数据
        //通过Socket得到输入流
        InputStream inputStream = socket.getInputStream();
        byte[] buf=new byte[1024];
        int readLen=0;
        StringBuilder stringBuilder = new StringBuilder();
        while ((readLen=inputStream.read(buf))!=-1){
            String s = new String(buf, 0, readLen);//根据读取到的长度，显示内容。
            stringBuilder.append(s);
        }
        System.out.println(stringBuilder);
        String downloadFilePath="src\\download\\";
        File file = new File(downloadFilePath);
        File[] files = file.listFiles();
        String temp="default.mp3";
        //判断是否存在客户端的请求下载的文件
        for (File file1:files){
            if (file1.isFile()){
                String fileName = file1.getName();
                int i = fileName.lastIndexOf(".");
                String name = fileName.substring(0,i);
                System.out.println(name);
                if (name.equals(stringBuilder.toString())){
                    temp=fileName;
                }
            }
        }
        //创建读取磁盘文件的输入流
        String filePath=downloadFilePath+temp;
        BufferedInputStream bufferedInputStream1 = new BufferedInputStream(new FileInputStream(filePath));
        //bytes就是filePath对应的字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream1);
        //通过socket获取到输出流,将bytes数据发送给服务端
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
        bufferedOutputStream.write(bytes);//将文件对应的字节数组的内容，写入到数据通道
        socket.shutdownOutput();//设置写入数据的结束标记

        //关闭其他资源
        bufferedOutputStream.close();
        bufferedInputStream1.close();
        inputStream.close();
        socket.close();
        serverSocket.close();

    }
}
